package com.ruoyi.generator.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.GenConstants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.text.CharsetKit;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.generator.domain.*;
import com.ruoyi.generator.domain.dto.*;
import com.ruoyi.generator.service.IGenTableColumnService;
import com.ruoyi.generator.service.IGenTableService;
import com.ruoyi.generator.util.GenUtils;
import com.ruoyi.generator.util.VelocityInitializer;
import com.ruoyi.generator.util.VelocityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.babyfish.jimmer.DraftObjects;
import org.babyfish.jimmer.Page;
import org.babyfish.jimmer.sql.JSqlClient;
import org.babyfish.jimmer.sql.ast.mutation.SaveMode;
import org.babyfish.jimmer.sql.ast.mutation.SimpleSaveResult;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/**
 * 业务 服务层实现
 *
 * @author ruoyi
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class GenTableServiceImpl implements IGenTableService {
    private final JSqlClient sqlClient;
    private final JdbcTemplate jdbcTemplate;
    private final IGenTableColumnService genTableColumnService;


    /**
     * 查询业务信息
     *
     * @param id 业务ID
     * @return 业务信息
     */
    @Override
    public GenTable selectGenTableById(String id) {
        GenTableTable table = GenTableTable.$;
        GenTableFetcher genTableFetcher = GenTableFetcher.$
                .allScalarFields()
                .crud()
                .tree()
                .sub()
                .treeCode()
                .treeParentCode()
                .treeName()
                .parentMenuId()
                .parentMenuName()
                .columns(
                        GenTableColumnFetcher.$
                                .allScalarFields()
                                .superColumn()
                                .usableColumn()
                                .capJavaField()
                                .readConverterExp()
                );
        return sqlClient.createQuery(table)
                .where(table.tableId().eq(id))
                .select(table.fetch(genTableFetcher
                ))
                .fetchOneOrNull();
    }


    /**
     * 查询业务列表
     *
     * @param input 业务信息
     * @return 业务集合
     */

    @Override
    public Page<GenTablePageView> selectGenTableList(GenTablePageInput input, PageQuery pageQuery) {
        GenTableTable table = GenTableTable.$;
        return sqlClient.createQuery(table)
                .where(
                        table.tableName().ilikeIf(input.getTableName()),
                        table.tableComment().ilikeIf(input.getTableComment())
                )
                .select(table.fetch(GenTablePageView.class))
                .fetchPage(pageQuery.getPageNum(), pageQuery.getPageSize());
    }

    /**
     * 查询据库列表
     *
     * @param input     业务信息
     * @param pageQuery 业务信息
     * @return 数据库表集合
     */

    @Override
    public Page<GenTableImportPageView> selectDbTableList(GenTablePageInput input, PageQuery pageQuery) {
        // jdbcTemplate.query("",);
        String dataSql = "select table_name , table_comment, create_time , update_time \n" +
                "from information_schema.tables\n" +
                "where table_schema = (select database())\n" +
                "  AND table_name NOT LIKE 'qrtz\\_%'\n" +
                "  AND table_name NOT LIKE 'gen\\_%'\n" +
                "  AND table_name NOT LIKE 'act\\_%'\n" +
                "  AND table_name NOT LIKE 'flw\\_%'\n" +
                "  AND table_name NOT IN (select table_name from gen_table)\n" +
                "order by create_time desc\n" +
                "LIMIT ? OFFSET ?";
        String countSql = "select count(1)\n" +
                "from information_schema.tables\n" +
                "where table_schema = (select database())\n" +
                "  AND table_name NOT LIKE 'qrtz\\_%'\n" +
                "  AND table_name NOT LIKE 'gen\\_%'\n" +
                "  AND table_name NOT LIKE 'act\\_%'\n" +
                "  AND table_name NOT LIKE 'flw\\_%'\n" +
                "  AND table_name NOT IN (select table_name from gen_table)\n" +
                "order by create_time desc";
        // 修复：正确计算OFFSET值并按正确顺序传递参数
        int pageSize = pageQuery.getPageSize();
        int pageNum = pageQuery.getPageNum();
        int offset = (pageNum) * pageSize;

        Object[] params = {pageSize, offset}; // LIMIT在前，OFFSET在后
        List<GenTableImportPageView> genTableImportPageViews = jdbcTemplate.query(dataSql, params, (rs, rowNum) -> {
            GenTableImportPageView view = new GenTableImportPageView();
            view.setTableName(rs.getString("table_name"));
            view.setTableComment(rs.getString("table_comment"));
            Timestamp createTime = rs.getTimestamp("create_time");
            view.setCreateTime(createTime != null ? createTime.toLocalDateTime() : null);
            Timestamp updateTime = rs.getTimestamp("update_time");
            view.setUpdateTime(updateTime != null ? updateTime.toLocalDateTime() : null);
            return view;
        });
        Long totalRecords = jdbcTemplate.queryForObject(countSql, Long.class);
        return new Page<>(genTableImportPageViews, totalRecords, pageQuery.getPageNum());
    }

    /**
     * 查询据库列表
     *
     * @param tableNames 表名称组
     * @return 数据库表集合
     */
    @Override
    public List<GenTableImportPageView> selectDbTableListByNames(String[] tableNames) {
        String tableNameStr = CollUtil.join(Arrays.asList(tableNames), "','");
        String dataSql = "select table_name, table_comment, create_time, update_time from information_schema.tables\n" +
                "\t\twhere table_name NOT LIKE 'qrtz\\_%' and table_name NOT LIKE 'gen\\_%' and table_schema = (select database())\n" +
                "\t\tand table_name in ('" + tableNameStr + "')";
        return jdbcTemplate.query(dataSql, (rs, rowNum) -> {
            GenTableImportPageView view = new GenTableImportPageView();
            view.setTableName(rs.getString("table_name"));
            view.setTableComment(rs.getString("table_comment"));
            Timestamp createTime = rs.getTimestamp("create_time");
            view.setCreateTime(createTime != null ? createTime.toLocalDateTime() : null);
            Timestamp updateTime = rs.getTimestamp("update_time");
            view.setUpdateTime(updateTime != null ? updateTime.toLocalDateTime() : null);
            return view;
        });
    }

    /**
     * 查询所有表信息
     *
     * @return 表信息集合
     */
    @Override
    public List<GenTable> selectGenTableAll() {
        GenTableTable table = GenTableTable.$;
        GenTableFetcher genTableFetcher = GenTableFetcher.$
                .allScalarFields()
                .columns(
                        GenTableColumnFetcher.$
                                .allScalarFields()
                );
        return sqlClient.createQuery(table)
                .select(table.fetch(genTableFetcher
                ))
                .execute();
    }

    /**
     * 修改业务
     *
     * @param genTable 业务信息
     * @return 结果
     */
    @Override
    @Transactional
    public void updateGenTable(GenTableSaveInput genTable) {
        String options = JSON.toJSONString(genTable.getParams());
        genTable.setOptions(options);
        int row = sqlClient.saveCommand(genTable.toEntity())
                .setMode(SaveMode.UPDATE_ONLY)
                .execute()
                .getTotalAffectedRowCount();
        /*if (row > 0) {
            for (GenTableColumn genTableColumn : genTable.getColumns()) {
                genTableColumnMapper.updateGenTableColumn(genTableColumn);
            }
        }*/
    }


    /**
     * 删除业务对象
     *
     * @param tableIds 需要删除的数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public void deleteGenTableByIds(String[] tableIds) {
        List<String> tableIdList = Arrays.asList(tableIds);
        sqlClient.deleteByIds(GenTable.class, tableIdList);
        GenTableColumnTable table = GenTableColumnTable.$;
        sqlClient.createDelete(table)
                .where(table.tableId().in(tableIdList))
                .execute();
    }

    /**
     * 创建表
     *
     * @param sql 创建表语句
     * @return 结果
     */
    @Override
    public boolean createTable(String sql) {
        jdbcTemplate.execute(sql);
        return true;
    }


    /**
     * 导入表结构
     *
     * @param tableList 导入表列表
     */
    @Override
    @Transactional
    public void importGenTable(List<GenTableImportPageView> tableList, String operName) {
        try {
            for (GenTableImportPageView table : tableList) {
                String tableName = table.getTableName();
                GenTable genTable = GenUtils.initTable(table, operName);
                SimpleSaveResult<GenTable> execute = sqlClient.saveCommand(genTable)
                        .setMode(SaveMode.INSERT_ONLY)
                        .execute();
                GenTable modifiedEntity = execute.getModifiedEntity();
                int row = execute
                        .getTotalAffectedRowCount();
                if (row > 0) {
                    // 保存列信息
                    List<GenTableColumnDbView> genTableColumns = genTableColumnService.selectDbTableColumnsByName(tableName);
                    for (GenTableColumnDbView column : genTableColumns) {
                        GenTableColumn genTableColumn = GenUtils.initColumnField(column, modifiedEntity);
                        sqlClient.saveCommand(genTableColumn)
                                .setMode(SaveMode.INSERT_ONLY)
                                .execute();
                    }
                }
            }
        } catch (Exception e) {
            throw new ServiceException("导入失败：" + e.getMessage());
        }
    }

    /**
     * 预览代码
     *
     * @param tableId 表编号
     * @return 预览数据列表
     */
    @Override
    public Map<String, String> previewCode(String tableId) {
        Map<String, String> dataMap = new LinkedHashMap<>();
        // 查询表信息
        GenTable table = this.selectGenTableById(tableId);
        // 设置主键列信息
        VelocityInitializer.initVelocity();
        GenTable subTable = null;
        if (StrUtil.isNotBlank(table.subTableName())) {
            subTable = this.selectGenTableByName(table.subTableName());

        }
        VelocityContext context = VelocityUtils.prepareContext(table, subTable);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.tplCategory(), table.tplWebType());
        for (String template : templates) {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, Constants.UTF8);
            tpl.merge(context, sw);
            dataMap.put(template, sw.toString());
        }
        return dataMap;
    }

    /**
     * 生成代码（下载方式）
     *
     * @param tableName 表名称
     * @return 数据
     */

    @Override
    public byte[] downloadCode(String tableName) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        generatorCode(tableName, zip);
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }

    /**
     * 生成代码（自定义路径）
     *
     * @param tableName 表名称
     */
    @Override
    public void generatorCode(String tableName) {
        // 查询表信息
        GenTable table = selectGenTableByName(tableName);
        // 设置主子表信息
        GenTable subTable = null;
        if (StrUtil.isNotBlank(table.subTableName())) {
            subTable = this.selectGenTableByName(table.subTableName());

        }

        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table, subTable);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.tplCategory(), table.tplWebType());
        for (String template : templates) {
            if (!StringUtils.containsAny(template, "sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm")) {
                // 渲染模板
                StringWriter sw = new StringWriter();
                Template tpl = Velocity.getTemplate(template, Constants.UTF8);
                tpl.merge(context, sw);
                try {
                    String path = getGenPath(table, subTable, template);
                    FileUtils.writeStringToFile(new File(path), sw.toString(), CharsetKit.UTF_8);
                } catch (IOException e) {
                    throw new ServiceException("渲染模板失败，表名：" + table.tableName());
                }
            }
        }
    }

    /**
     * 同步数据库
     *
     * @param tableName 表名称
     */
    @Override
    @Transactional
    public void synchDb(String tableName) {
        GenTable table = selectGenTableByName(tableName);
        List<GenTableColumn> tableColumns = table.columns();
        Map<String, GenTableColumn> tableColumnMap = tableColumns.stream().collect(Collectors.toMap(GenTableColumn::columnName, Function.identity()));

        List<GenTableColumnDbView> dbTableColumns = genTableColumnService.selectDbTableColumnsByName(tableName);
        if (StringUtils.isEmpty(dbTableColumns)) {
            throw new ServiceException("同步数据失败，原表结构不存在");
        }
        List<String> dbTableColumnNames = dbTableColumns.stream().map(GenTableColumnDbView::getColumnName).toList();

        dbTableColumns.forEach(view -> {
            GenTableColumn genTableColumn = GenUtils.initColumnField(view, table);
            if (tableColumnMap.containsKey(genTableColumn.columnName())) {
                GenTableColumn produce = GenTableColumnDraft.$.produce(genTableColumn, column -> {
                    GenTableColumn prevColumn = tableColumnMap.get(genTableColumn.columnName());
                    column.setColumnId(prevColumn.columnId());
                    if (Boolean.TRUE.equals(genTableColumn.isList())) {
                        // 如果是列表，继续保留查询方式/字典类型选项
                        column.setDictType(prevColumn.dictType());
                        column.setQueryType(prevColumn.queryType());
                    }
                    if (prevColumn.isRequired() != null && Boolean.FALSE.equals(genTableColumn.isPk())
                            && (Boolean.TRUE.equals(genTableColumn.isInsert()) || Boolean.TRUE.equals(genTableColumn.isEdit()))
                            && ((genTableColumn.isUsableColumn()) || (!genTableColumn.isSuperColumn()))) {
                        // 如果是(新增/修改&非主键/非忽略及父属性)，继续保留必填/显示类型选项
                        column.setIsRequired(prevColumn.isRequired());
                        column.setHtmlType(prevColumn.htmlType());
                    }
                    // 旧的配置（插入、编辑、列表、查询、查询方式、必填、显示类型、字典类型等不再进行配置）
                    DraftObjects.unload(column, GenTableColumnProps.IS_REQUIRED);
                    DraftObjects.unload(column, GenTableColumnProps.IS_EDIT);
                    DraftObjects.unload(column, GenTableColumnProps.IS_INSERT);
                    DraftObjects.unload(column, GenTableColumnProps.IS_LIST);
                    DraftObjects.unload(column, GenTableColumnProps.IS_QUERY);
                    DraftObjects.unload(column, GenTableColumnProps.QUERY_TYPE);
                    DraftObjects.unload(column, GenTableColumnProps.QUERY_TYPE);
                    DraftObjects.unload(column, GenTableColumnProps.HTML_TYPE);
                    DraftObjects.unload(column, GenTableColumnProps.DICT_TYPE);
                });

                sqlClient.saveCommand(produce)
                        .setMode(SaveMode.UPDATE_ONLY)
                        .execute();
            } else {
                sqlClient.saveCommand(genTableColumn)
                        .setMode(SaveMode.INSERT_ONLY)
                        .execute();
            }
        });
        List<GenTableColumn> delColumns = tableColumns.stream()
                .filter(column -> !dbTableColumnNames.contains(column.columnName()))
                .collect(Collectors.toList());
        if (StringUtils.isNotEmpty(delColumns)) {
            List<String> list = delColumns.stream().map(GenTableColumn::columnId).toList();
            sqlClient.deleteByIds(GenTableColumn.class, list);
        }
    }


    /**
     * 批量生成代码（下载方式）
     *
     * @param tableNames 表数组
     * @return 数据
     */
    @Override
    public byte[] downloadCode(String[] tableNames) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames) {
            generatorCode(tableName, zip);
        }
        IOUtils.closeQuietly(zip);
        return outputStream.toByteArray();
    }


    /**
     * 查询表信息并生成代码
     */

    private void generatorCode(String tableName, ZipOutputStream zip) {
        // 查询表信息
        GenTable table = selectGenTableByName(tableName);
        // 设置主子表信息
        GenTable subTable = null;
        if (StrUtil.isNotBlank(table.subTableName())) {
            subTable = selectGenTableByName(table.subTableName());
        }

        VelocityInitializer.initVelocity();

        VelocityContext context = VelocityUtils.prepareContext(table, subTable);

        // 获取模板列表
        List<String> templates = VelocityUtils.getTemplateList(table.tplCategory(), table.tplWebType());
        for (String template : templates) {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, Constants.UTF8);
            tpl.merge(context, sw);
            try {
                // 添加到zip
                zip.putNextEntry(new ZipEntry(VelocityUtils.getFileName(template, table, subTable)));
                IOUtils.write(sw.toString(), zip, Constants.UTF8);
                IOUtils.closeQuietly(sw);
                zip.flush();
                zip.closeEntry();
            } catch (IOException e) {
                log.error("渲染模板失败，表名：" + table.tableName(), e);
            }
        }
    }


    /**
     * 修改保存参数校验
     *
     * @param genTable 业务信息
     */
    @Override
    public void validateEdit(GenTableSaveInput genTable) {
        if (GenConstants.TPL_TREE.equals(genTable.getTplCategory())) {
            String options = JSON.toJSONString(genTable.getParams());
            JSONObject paramsObj = JSON.parseObject(options);
            if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE))) {
                throw new ServiceException("树编码字段不能为空");
            } else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE))) {
                throw new ServiceException("树父编码字段不能为空");
            } else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME))) {
                throw new ServiceException("树名称字段不能为空");
            }
        } else if (GenConstants.TPL_SUB.equals(genTable.getTplCategory())) {
            if (StringUtils.isEmpty(genTable.getSubTableName())) {
                throw new ServiceException("关联子表的表名不能为空");
            } else if (StringUtils.isEmpty(genTable.getSubTableFkName())) {
                throw new ServiceException("子表关联的外键名不能为空");
            }
        }
    }

    public GenTable selectGenTableByName(String subTableName) {
        GenTableTable table = GenTableTable.$;
        GenTableFetcher genTableFetcher = GenTableFetcher.$
                .allScalarFields()
                .columns(
                        GenTableColumnFetcher.$
                                .allScalarFields()
                );
        return sqlClient.createQuery(table)
                .where(table.tableName().eq(subTableName))
                .select(table.fetch(genTableFetcher
                ))
                .fetchOneOrNull();
    }


    /**
     * 设置代码生成其他选项值
     *
     * @param genTable 设置后的生成对象
     */

/*    public GenTable setTableFromOptions(GenTable genTable) {
        JSONObject paramsObj = JSON.parseObject(genTable.options());
        if (StringUtils.isNotNull(paramsObj)) {
            String treeCode = paramsObj.getString(GenConstants.TREE_CODE);
            String treeParentCode = paramsObj.getString(GenConstants.TREE_PARENT_CODE);
            String treeName = paramsObj.getString(GenConstants.TREE_NAME);
            Long parentMenuId = paramsObj.getLongValue(GenConstants.PARENT_MENU_ID);
            String parentMenuName = paramsObj.getString(GenConstants.PARENT_MENU_NAME);
            return GenTableDraft.$.produce(genTable, draft -> {
                draft.setTreeCode(treeCode);
                draft.setTreeParentCode(treeParentCode);
                draft.setTreeName(treeName);
                draft.setParentMenuId(parentMenuId);
                draft.setParentMenuName(parentMenuName);
            });
        }
        return genTable;
    }*/

    /**
     * 获取代码生成地址
     *
     * @param table    业务表信息
     * @param template 模板文件路径
     * @return 生成地址
     */
    public static String getGenPath(GenTable table, GenTable subTable, String template) {
        String genPath = table.genPath();
        if (StringUtils.equals(genPath, "/")) {
            return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table, subTable);
        }
        return genPath + File.separator + VelocityUtils.getFileName(template, table, subTable);
    }
}
